package flc.ast.utils;

import android.os.Build;
import android.os.Handler;
import android.os.Looper;

import com.blankj.utilcode.util.ToastUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;

public class TCPClient {
    // 回调接口
    public interface ClientListener {
        void onConnected();

        void onConnectionFailed(String error);

        void onDisconnected();

        void onMessageReceived(String message);

        void onError(String error);

        void onStatisticsUpdated(int receivedCount, int sentCount, double receiveSpeed, double sendSpeed, int failedCount);
    }

    // 通知连接成功
    private void notifyConnected() {
        mainHandler.post(() -> {
            if (listener != null) listener.onConnected();
            startTime = System.currentTimeMillis();
        });
    }

    // 更新统计信息
    private void updateStatistics() {
        if (listener == null) return;

        long currentTime = System.currentTimeMillis();
        double elapsedTime = (currentTime - startTime) / 1000.0; // 秒

        double receiveSpeed = elapsedTime > 0 ? receivedBytes / elapsedTime : 0; // B/s
        double sendSpeed = elapsedTime > 0 ? sentBytes / elapsedTime : 0; // B/s

        mainHandler.post(() -> {
            listener.onStatisticsUpdated(receivedCount, sentCount, receiveSpeed, sendSpeed, failedCount);
        });
    }

    // 通知连接失败
    private void notifyConnectionFailed(final String error) {
        mainHandler.post(() -> {
            if (listener != null) listener.onConnectionFailed(error);
        });
    }

    // 通知断开连接
    private void notifyDisconnected() {
        mainHandler.post(() -> {
            if (listener != null) listener.onDisconnected();
        });
    }

    // 通知接收到消息
    private void notifyMessageReceived(final String message) {
        mainHandler.post(() -> {
            if (listener != null) listener.onMessageReceived(message);
        });
    }

    // 通知错误
    private void notifyError(final String error) {
        mainHandler.post(() -> {
            if (listener != null) listener.onError(error);
        });
    }

    private ClientListener listener;
    private Handler mainHandler = new Handler(Looper.getMainLooper());
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    private String receiveCharsetName = "UTF-8"; // 接收消息的字符编码
    private String sendCharsetName = "UTF-8";   // 发送消息的字符编码
    private ExecutorService executor = Executors.newSingleThreadExecutor();
    private boolean isConnected = false;

    // 统计信息
    private int receivedCount = 0;        // 接收消息计数
    private int sentCount = 0;            // 发送消息计数
    private long receivedBytes = 0;       // 接收总字节数
    private long sentBytes = 0;           // 发送总字节数
    private long startTime = 0;           // 开始统计时间
    private int failedCount = 0;          // 失败次数

    // 设置回调监听器
    public void setClientListener(ClientListener listener) {
        this.listener = listener;
    }

    // 设置接收消息的字符编码
    public void setReceiveCharsetName(String charsetName) {
        if (charsetName != null && !charsetName.isEmpty()) {
            this.receiveCharsetName = charsetName;
        }
    }

    // 设置发送消息的字符编码
    public void setSendCharsetName(String charsetName) {
        if (charsetName != null && !charsetName.isEmpty()) {
            this.sendCharsetName = charsetName;
        }
    }

    public boolean isConnected() {
        return isConnected;
    }

    public void connect(String serverIp, int port) {
        // Reinitialize executor if it's shut down or terminated
        if (executor.isShutdown() || executor.isTerminated()) {
            executor = Executors.newSingleThreadExecutor();
        }
        executor.execute(() -> {
            try {
                socket = new Socket();
//                socket.bind(new InetSocketAddress(port));
                socket.connect(new InetSocketAddress(serverIp, port), 5000);
                // 修改connect方法中的输出流初始化部分
                try {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        out = new PrintWriter(socket.getOutputStream(), true, Charset.forName(sendCharsetName));
                    } else {
                        // 恢复低版本系统的初始化代码
                        out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), sendCharsetName), true);
                    }
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream(), Charset.forName(receiveCharsetName)));
                    isConnected = true;
                    notifyConnected();
                } catch (UnsupportedEncodingException e) {
                    failedCount++;
                    notifyConnectionFailed("不支持的字符编码: " + e.getMessage());
                    updateStatistics();
                    try {
                        socket.close();
                    } catch (IOException ex) {
                        // 忽略关闭socket的异常
                    }
                }

                String response;
                while ((response = in.readLine()) != null) {
                    if (socket != null && socket.isConnected()) {
                        String senderIp = socket.getInetAddress().getHostAddress();
                        int senderPort = socket.getPort();
                        response = "[" + senderIp + ":" + senderPort + "]" + response;
                    }
                    final String msg = response;
                    receivedCount++;
                    receivedBytes += msg.getBytes().length;
                    notifyMessageReceived(msg);
                    updateStatistics();
                }

//                // 服务器断开连接
//                if (isConnected) {
//                    disconnect();
//                    notifyDisconnected();
//                }
            } catch (final IOException e) {
                if (!isConnected) {
                    failedCount++;
                    notifyConnectionFailed(e.getMessage());
                    updateStatistics();
                } else {
                    failedCount++;
                    notifyError(e.getMessage());
                    updateStatistics();
                }
            }
        });
    }

    public void sendMessage(String message) {
        if (!isConnected || out == null) {
            notifyError("未连接到服务器或输出流未初始化");
            return;
        }
//        // 关键修复：检查线程池状态，如已关闭则重新初始化
//        if (executor.isShutdown() || executor.isTerminated()) {
//            executor = Executors.newSingleThreadExecutor();
//            ToastUtils.showShort("线程池已重启");
//        }
        new Thread(()->{
            if (out != null) {
                out.println(message);
                out.flush(); // 显式刷新确保数据发送
                sentCount++;
                sentBytes += message.getBytes().length;
                updateStatistics();
            }
        }).start();
    }

    public void disconnect() {
        if (!isConnected) return;
        isConnected = false;
        executor.shutdown();
        try {
            if (out != null) out.close();
            if (in != null) in.close();
            if (socket != null) socket.close();
            notifyDisconnected();
        } catch (IOException e) {
            notifyError(e.getMessage());
        }
    }
}
